#!/bin/bash
#
#######################################################################
# Title      :Reasy E17
# Author     :Dave Andreoli {dave@gurumeditaiton.it}
# Requires   :a debian based distro (preferred)
# License    :LGPL
#######################################################################
# Description
#   This script will help you install EFL and enlightenment17 on your system.
#   You can configure some aspect from the first part of this file.
#   The script need a way to become root to install the compiled packages
#   on your system. By default it use the 'sudo' command, but you can change
#   it from the config section.
#   I suggest to start with a standard installation and then add
#   more components as you need.
#
#   You can find the ChangeLog at the end of this file
#######################################################################
#
# TODO
#   - set an option to also generate docs
#   - show readme file of packages
#   - at the end launch a cool showcase
#
# BUGS
#   - sudo will ask you the password breaking the dialogs
#   - if you resize the window the current operation (compile) abort
#     (on ubuntu, not on opensuse)
#
# DEBUG NOTE:
#   To debug start the script as:
#     ./ReasyE17.sh 2>> tmpfile
#   then in another terminal do:
#     tail -f tmpfile
#   and in the script to debug use stderr:
#     echo "Hallo World!" >&2
#
###############################################################


###############################################################
# Configuration
###############################################################

E_USER=             # leave blank for anonymous access or
                    #  use your E svn/git name
SUDO="sudo"         # how to become root
DEF_W=0             # dialogs width (0 = auto)
DEF_H=0             # dialogs height (0 = auto)
DEF_M=0             # dialogs menu size (0 = auto)
PREFIX="/usr/local" # change at your own risk
DIALOG="dialog"     # not working alternative: gdialog, zenity
DELAY=3             # seconds to wait before deleting dialogs
PYTHON="python"     # you can change to python3
XSESSIONS_DIR="/usr/share/xsessions/"
SUGGESTED_FLAGS="--disable-physics"
MAKE="make"
INSTALL="$SUDO make install"
UNINSTALL="$SUDO make uninstall"
LDCONFIG="/sbin/ldconfig"

# choose correct repo
if [ -z "$E_USER" ]; then
   e_git="git://git.enlightenment.org"
   e_svn="http://svn.enlightenment.org/svn/e/trunk"
else
   e_git="ssh://git@git.enlightenment.org"
   e_svn="svn+ssh://${E_USER}@svn.enlightenment.org/var/svn/e/trunk"
fi

###############################################################
# Packages list
###############################################################

declare -a DEFAULT_LIST=(
   core/efl
   core/evas_generic_loaders
   core/emotion_generic_players
   core/elementary
   core/enlightenment
   bindings/Cython-0.17.3
   bindings/python-efl
   apps/terminology
   apps/econnman
)

declare -a FULL_LIST=(
   ${DEFAULT_LIST[*]}
   apps/ecrire
   tools/clouseau
   tools/exactness
   tools/expedite
   tools/formatting
   tools/geneet
   games/etrophy
   games/e_cho
   games/econcentration
   games/efbb
   games/elemines
   misc/entrance
   emodules/penguins
   emodules/places
   apps/valosoitin
   apps/apathy
   apps/epour
)

# Define where to fetch the packages
declare -A VCS_URLS=(
   [core/efl]="GIT:$e_git/core/efl.git"
   [core/evas_generic_loaders]="GIT:$e_git/core/evas_generic_loaders.git"
   [core/emotion_generic_players]="GIT:$e_git/core/emotion_generic_players.git"
   [core/elementary]="GIT:$e_git/core/elementary.git"
   [core/enlightenment]="GIT:$e_git/core/enlightenment.git"
   [bindings/Cython-0.17.3]="PKG:http://www.cython.org/release/Cython-0.17.3.tar.gz"
   [bindings/python-efl]="GIT:$e_git/bindings/python/python-efl.git"
   [tools/clouseau]="GIT:$e_git/tools/clouseau.git"
   [tools/expedite]="GIT:$e_git/tools/expedite.git"
   [tools/exactness]="GIT:$e_git/tools/exactness.git"
   [tools/formatting]="GIT:$e_git/tools/formatting.git"
   [tools/geneet]="GIT:$e_git/tools/geneet.git"
   [apps/econnman]="GIT:$e_git/apps/econnman.git"
   [apps/ecrire]="GIT:$e_git/apps/ecrire.git"
   [apps/terminology]="GIT:$e_git/apps/terminology.git"
   [misc/entrance]="GIT:$e_git/misc/entrance.git"
   [games/etrophy]="GIT:$e_git/games/etrophy.git"
   [games/e_cho]="GIT:$e_git/games/e_cho.git"
   [games/econcentration]="GIT:$e_git/games/econcentration.git"
   [games/elemines]="GIT:$e_git/games/elemines.git"
   [games/efbb]="GIT:$e_git/games/efbb.git"
   [emodules/penguins]="GIT:$e_git/enlightenment/modules/penguins.git"
   [emodules/places]="GIT:$e_git/enlightenment/modules/places.git"
   [apps/valosoitin]="BZR:lp:valosoitin"
   [apps/apathy]="BZR:lp:apathy"
   [apps/epour]="BZR:lp:epour"
)

# Define a description for the packages
declare -A DESCRS=(
   [core/efl]="Core libs"
   [core/evas_generic_loaders]="Evas loaders"
   [core/emotion_generic_players]="Emotion loaders"
   [core/elementary]="GUI Toolkit"
   [core/enlightenment]="The E17 Window Manager"
   [tools/clouseau]="An UI inspection tool"
   [tools/exactness]="Elm pixel regression tester"
   [tools/expedite]="Evas benchmarking tool"
   [tools/formatting]="EFL formatting tools"
   [tools/geneet]="EET code generator"
   [apps/econnman]="ConnMan GUI written in Python"
   [apps/ecrire]="Simple text editor"
   [apps/terminology]="EFL terminal emulator"
   [misc/entrance]="EFL display manager"
   [bindings/Cython-0.17.3]="Cython 0.17.3"
   [bindings/python-efl]="Python EFL 1.8"
   [emodules/penguins]="E17 penguins module"
   [emodules/places]="E17 volume manager"
   [games/etrophy]="Record library"
   [games/e_cho]="Simon Like emulator"
   [games/econcentration]="Menory game"
   [games/elemines]="A minesweeper clone"
   [games/efbb]="A Physics game"
   [apps/valosoitin]="An audio player"
   [apps/apathy]="An audio player"
   [apps/epour]="A BitTorrent Client"
)


###############################################################
# How to resolv dependencies on various distro
###############################################################

RESOLV_UBUNTU="apt-get -y install wget curl subversion git cvs bzr build-essential
autoconf automake autopoint gettext pkg-config libtool autotools-dev
zlib1g-dev libpng12-dev libjpeg-dev libgif-dev libtiff4-dev
libfreetype6-dev libxcb-shape0-dev libx11-dev libxp-dev libxtst-dev
libxext-dev libxrender-dev libxinerama-dev libxcb-keysyms1-dev
libxcursor-dev libxrandr-dev libxdamage-dev libxcomposite-dev
libxss-dev libssl-dev libcurl4-openssl-dev libfribidi-dev
libdbus-1-dev libpam0g-dev libxml2-dev libxslt1-dev libltdl3-dev
libgl1-mesa-dev libglu1-mesa-dev python-dev librsvg2-dev
libtag1-dev libtagc0-dev libxine-dev libsqlite3-dev fontconfig
libfontconfig-dev liblua5.1-dev libc-ares-dev libexif-dev
libcanberra-dev libudev-dev libvlc-dev libsndfile1-dev libmount-dev
libblkid-dev check libpulse-dev"


RESOLV_DEBIAN="apt-get -y install wget curl subversion git cvs bzr autoconf
automake gettext build-essential pkg-config libtool autotools-dev check
zlib1g-dev libjpeg-dev libgif-dev libtiff5-dev librsvg2-dev libfreetype6-dev
libx11-dev libpng12-dev libxext-dev libxp-dev libxtst-dev libxrender-dev
libxinerama-dev libxcursor-dev libxrandr-dev libxdamage-dev libxcb-shape0-dev
libxcb-keysyms1-dev libxcomposite-dev libpam-dev libxss-dev libssl-dev
libfribidi-dev libdbus-1-dev libcurl3-dev libxml2-dev libxslt1-dev libltdl3-dev
libtag1-dev libtagc0-dev libxine-dev libsqlite3-dev libfontconfig1-dev
liblua5.1-dev libsndfile1-dev libpulse-dev libudev-dev libmount-dev libblkid-dev
libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev libvlc-dev python-dev
mesa-common-dev libgles2-mesa-dev"


###############################################################
# Implementation
###############################################################

PNAME='Reasy E17'
PVER='0.4.2'
BTITLE="$PNAME v$PVER - davemds EFL Installer"
HELP="Move using [UP] [DOWN], [Enter] to select"
HELP2="Move using [UP] [DOWN], [Space] to select"
WELCOME="\nWelcome!\n
This script will help you install enlightenment17 on your system.
Before running the Install procedure you need to install all the
external dependencies. If you are on a supported distro you just
have to use the Check Dependencies in Menu.\n
You can choose between 2 different set of packages, the standard one include
enlightenment and the necessary libs to run it.
The full one instead will install all the know working packages from svn.
But you can also define one ore more custom set to reuse later."



### Main Menu
function re_main_menu
{
   $DIALOG --backtitle "$BTITLE" --title " Main Menu " --cancel-label "Quit" \
           --menu "Move using [UP], [DOWN] and [Enter] to select" \
           $DEF_H $DEF_W $DEF_M \
           Check "Install external dependencies" \
           Download "Checkout, download or update" \
           Build "Compile and Install packages" \
           Update "Download + Build" \
           Config "Configure the script" \
           Logs "View configure output" \
           Quit "Exit" 2>$_temp
   [ "$?" == "0" ] || re_exit 0

   ACTION=`cat $_temp`
   case $ACTION in
      Check)     re_install_dep;;
      Download)  re_target_menu;;
      Build)     re_target_menu;;
      Update)    re_target_menu;;
      Config)    re_config_menu;;
      Logs)      re_logs_menu;;
      Quit)      re_exit 0;;
   esac
}

### Config Menu
function re_config_menu
{
   $DIALOG --backtitle "$BTITLE" --no-cancel \
           --title " $PNAME Configuration [step 1 di 1] " \
           --default-item "$DISTRO" \
           --menu "Choose the distro that is closer to the one installed on this system.\n$HELP" \
           $DEF_H $DEF_W $DEF_M \
           Ubuntu "Ubuntu" \
           Debian "Debian" \
           Unknown "Other (only experts)" 2> $_temp
   [ "$?" ==  "0" ] && DISTRO=`cat $_temp` || DISTRO="Unknown"

   $DIALOG --backtitle "$BTITLE" --no-cancel \
           --title " $PNAME Configuration [step 2 di 2] " \
           --inputbox "Choose your configuration options, common choices:\n$SUGGESTED_FLAGS\n" \
           $DEF_H $DEF_W "$OPTIONS"  2> $_temp
   [ "$?" ==  "0" ] && OPTIONS=`cat $_temp` || OPTIONS=""

   re_save_config
}

### Save configuration to config file
function re_save_config
{
   echo "DISTRO=$DISTRO" > $_conf
   echo "OPTIONS=\"$OPTIONS\"" >> $_conf
   echo "CUSTOMS=\"$CUSTOMS\"" >> $_conf
}

### Ask the type of target (standard, full or custom)
function re_target_menu
{
   local desc=

   > $_temp_list
   echo "Standard \"main, more stable, packages\"" >> $_temp_list
   echo "Full \"$ACTION all packages\"" >> $_temp_list
   echo "Single \"$ACTION a single package\"" >> $_temp_list
   echo "------- -----------------------" >> $_temp_list
   for name in $CUSTOMS; do
      desc=`cat reasy.custom.$name | head -1`
      echo "$name \"$desc\"" >> $_temp_list
   done
   echo "Create \"Create a new selection of packages\"" >> $_temp_list

   $DIALOG --backtitle "$BTITLE" --title " Choose $ACTION target " \
           --menu "$HELP" $DEF_H $DEF_W $DEF_M \
           --file "$_temp_list" \
            2> $_temp
   [ "$?" ==  "0" ] || return

   TARGET=`cat $_temp`
   case $TARGET in
      Standard) re_confirm_action;;
      Full)     re_confirm_action;;
      Single)   re_single_target_menu;;
      Create)   re_add_custom_target;;
      *)        re_custom_target_menu $TARGET;;
   esac
}

### Add a new custom target list
function re_add_custom_target
{
   local name=
   local desc=

   # ask for the name
   $DIALOG --backtitle "$BTITLE" --title "Add list" \
              --inputbox "Insert the name of the new packages list.\n
NO SPACE ALLOWED! nor any other special chars." \
              16 51 2> $_temp
   [ "$?" ==  "0" ] || re_target_menu
   name=`cat $_temp`

   # the description
   $DIALOG --backtitle "$BTITLE" --title "Add list" \
           --inputbox "Now a really short description (3/5 words)." \
           16 51 2> $_temp
   [ "$?" ==  "0" ] || re_target_menu
   desc=`cat $_temp`

   # TODO check $name & $descr not null

   # TODO check name exist (or not?)

   # save all
   CUSTOMS="$CUSTOMS $name"
   echo $desc > reasy.custom.$name
   re_save_config

   # back where we where (hopefully..)
   re_target_menu
}

### Show list of available logs
function re_logs_menu
{
   local log=

   > $_temp_list
   for log in `ls -a .*.info`; do
      echo "$log \"\"" >> $_temp_list
   done
   for log in `ls -a */*.info`; do
      echo "$log \"\"" >> $_temp_list
   done

   while true; do
      $DIALOG --backtitle "$BTITLE" --cancel-label "Back" \
              --title " Select the log to show " \
              --menu "$HELP" \
              $DEF_H $DEF_W $DEF_M --file $_temp_list 2> $_temp
      [ "$?" ==  "0" ] || break

      logname=`cat $_temp`
      $DIALOG --backtitle "$BTITLE" --exit-label "Close" \
              --title " Log file   [Up] [Down] [Left] [Right] to scroll " \
              --textbox $logname $DEF_H $DEF_W
   done
}

### Custom target menu (list all the packages)
function re_custom_target_menu
{
   local name=$1  # ARG1: the name of the custom to show
   local custom_file="reasy.custom.$name"
   local desc=`cat $custom_file | head -1`

   > $_temp_list
   for package in ${FULL_LIST[*]}; do
      cat $custom_file | grep -x $package > /dev/null
      [ "$?" == 0 ] && status="on" || status="off"
      echo "$package \"${DESCRS[$package]}\" $status" >> $_temp_list
   done

   $DIALOG --separate-output --backtitle "$BTITLE" \
           --title " Select package to $ACTION " \
           --checklist "$HELP2" \
           $DEF_H $DEF_W $DEF_M --file $_temp_list 2> $_temp
   [ "$?" ==  "0" ] || return

   # save the custom file...maybe user changed something
   CUSTOM_LIST=`cat "$_temp"`
   echo "$desc" > $custom_file
   cat $_temp >> $custom_file
   re_confirm_action
}

### Single target menu (list all the packages)
function re_single_target_menu
{
   > $_temp_list
   for package in ${FULL_LIST[*]}; do
      echo "$package \"${DESCRS[$package]}\"" >> $_temp_list
   done

   $DIALOG --backtitle "$BTITLE" \
           --title " Select the package to $ACTION " \
           --menu "$HELP" \
           $DEF_H $DEF_W $DEF_M --file $_temp_list 2> $_temp
   [ "$?" ==  "0" ] || return

   SINGLE_LIST=`cat "$_temp"`
   re_confirm_action
}

### Ask the user to confirm the action to perform 
function re_confirm_action()
{
   case $TARGET in
      Standard) LIST=(${DEFAULT_LIST[@]});;
      Full)     LIST=(${FULL_LIST[@]});;
      Single)   LIST=(${SINGLE_LIST[@]});;
      *)        LIST=(${CUSTOM_LIST[@]});;
   esac

   local count=${#LIST[@]}
   if [ "$count" -lt 1 ]; then
      re_message "\n\nERROR: No package selected."
      return
   fi

   # build info text
   local txt="Now I'm going to $ACTION $count packages, check if the list is \
correct and confirm the action.\n\nPackages:"
   for package in ${LIST[@]}; do
      txt="$txt `basename $package`,"
   done
   txt=${txt%?}
   txt="$txt\n\nPress [Yes] to $ACTION $count packages or [No] to return \
to the main menu."

   # yes/no dialog
   $DIALOG --backtitle "$BTITLE" --title " Confirm $ACTION of $count packages " \
           --defaultno --yesno "$txt" $DEF_H $DEF_W
   [ "$?" ==  "0" ] || return

   # and finally start the execution
   re_exec_action
}

### Exec the selected aciotn
function re_exec_action()
{
   case $ACTION in
      Download)  re_download_list;;
      Build)     re_compile_list;;
      Update)    re_download_list;re_compile_list;;
      *) re_message "ERROR: unknown action '$ACTION'";;
   esac

   if [ "$RET" == 0 ]; then
      # successfull dialog with the ability to view logs
      local ret=2
      while [ $ret -eq 2 ]; do
         $DIALOG --backtitle "$BTITLE" --title " Report " \
              --help-button --help-label "View log" \
              --msgbox "\n\n$ACTION of $count packages completed successfully :)" \
              $DEF_H $DEF_W
         ret=$?
         [ "$ret" == 2 ] && re_show_log
      done
   fi
}

###############################################################

### Install all the required dependencies
function re_install_dep
{
   case $DISTRO in
      Ubuntu)  resolv=$RESOLV_UBUNTU;;
      Debian)  resolv=$RESOLV_DEBIAN;;
      *)       resolv_="";;
   esac

   re_execute "$SUDO $resolv" "." "Installing required packages" "" \
"Error while installing external dependencies.\n\n\
Check your internet connection. Probably your distribution is not supported \
or some packages are changed.\n\nCheck the log for more info."
   [ "$RET" == "0" ] && re_message "\n\nAll dependencies installed correctly"
}

### Checkout, download or Update packages in $LIST
function re_download_list
{
   local i=1
   local tot=${#LIST[@]}
   local url=
   local cmd=
   local working_dir=

   for package in ${LIST[@]}; do
      working_dir="$_pwd"
      url=${VCS_URLS[$package]}

      case "$url" in
         GIT:*)
            if [ -d $package ]; then
               cmd="git pull"
               working_dir="$_pwd/$package"
               # FIXME Stupid hack (sorry translators)
               if [ -e "$package/po" ]; then
                  pushd $working_dir
                  git checkout po/*.po
                  popd
               fi
            else
               cmd="git clone ${url:4} $package --progress"
            fi
            ;;
         SVN:*)
            if [ -d $package ]; then
               cmd="svn update"
               working_dir="$_pwd/$package"
               # FIXME Stupid hack (sorry translators)
               [ -e "$package/po" ] && rm -f $package/po/*
            else
               cmd="svn checkout ${url:4} $package"
            fi
            ;;
         BZR:*)
            if [ -d $package ]; then
               cmd="bzr merge"
               working_dir="$_pwd/$package"
            else
               dir=`dirname $package`
               [ ! -d "$dir" ] && mkdir -p "$dir"
               cmd="bzr branch -q ${url:4} $package"
            fi
            ;;
         PKG:*)
            if [ -d $package ]; then
               continue # Packages doesn't change, no need to re-download !!
            else
               dir=`dirname $package`
               [ ! -d "$dir" ] && mkdir -p "$dir"
               cmd="curl -s ${url:4} | tar xzv -C $dir"
            fi
            ;;
        *) echo "UNKNOW Version Control System";;
      esac

      re_execute "$cmd" "$working_dir" " Downloading $package ($i of $tot) " \
                 "'$cmd' in folder: '$working_dir'" \
"Error while downloading '$package'\n\n\
Probably the svn server is unreacheable or your connection is down.\n\
But you can also try to remove the source of this package and reinstall, \
sometimes svn can't manage the situation and fail.\n\n\
Most of the time you just have to press the 'Retry' button."
      [ "$RET" == 0 ] || return
      [ "$_ret" == 3 ] && continue # skip pressed

      let i++
   done 
}

### Compile and Install packages in $LIST
function re_compile_list
{
   local i=1
   local tot=${#LIST[@]}
   local opts=
   
   for package in ${LIST[@]}; do

      # Distutils (setup.py)
      if [ -e $package/setup.py ]; then
         re_execute "$SUDO $PYTHON setup.py install" "$_pwd/$package" \
                    " Installing $package ($i of $tot) " \
                    "[1/1] (sudo) $PYTHON setup.py install " \
"Error while executing setup.py of '$package'\n\n\
This probably means that you miss some external dependecies.\n\
Look at the log for more info"

      # Autotools
      elif [ -e $package/autogen.sh ]; then
         opts="--prefix=$PREFIX $OPTIONS"
         # autogen.sh
         re_execute "./autogen.sh $opts" "$_pwd/$package" \
                    " Installing $package ($i of $tot) " \
                    "[1/3] AutoGenerate (./autogen.sh $opts)" \
"Error while executing autogen.sh of '$package'\n\n\
This probably means that you miss some external dependecies.\n\
Look at the log for more info"
         [ "$RET" == 0 ] || return # command result is ok
         [ "$_ret" == 3 ] && continue # skip pressed

         # Save the configure output to named files
         case $package in
            core/*)
            cp "$_log" "$_pwd/$package.info"
         ;;
         esac

         # make
         re_execute "$MAKE" "$_pwd/$package" \
                    " Installing $package ($i of $tot) " \
                    "[2/3] Compiling ($MAKE)" \
"Error while executing make on '$package'\n\n\
Probably something is changed in svn, try to first update the dependency.\n"
         [ "$RET" == 0 ] || return
         [ "$_ret" == 3 ] && continue

         # sudo make install
         re_execute "$INSTALL" "$_pwd/$package" \
                     " Installing $package ($i of $tot) " \
                     "[3/3] Installing as root ($INSTALL)" \
"Error while installing '$package'\n\n\
TODO write a possible reason.\n\
TODO write a possible solution"
         [ "$RET" == 0 ] || return
         [ "$_ret" == 3 ] && continue

      else
         re_messagge "ERROR: Unsupported build system"
      fi

      # hack to install e17 xsession file in non-standard places
      [ "$package" == "core/enlightenment" ] && re_install_xsession

      let i++
      $SUDO $LDCONFIG
   done
}

### Install the xsession file
function re_install_xsession
{
   #TODO fix path when implement different installation path
   
   # a stupid fix for stupid login manager that don't look in /usr/local
   install -d "$XSESSIONS_DIR"
   re_execute "$SUDO cp core/enlightenment/data/xsession/enlightenment.desktop $XSESSIONS_DIR" "$_pwd" \
               " Installing Xsession file " \
               "Install the Xsession file in '$XSESSIONS_DIR'" \
               "\nError while copy the Xsession file in '$XSESSIONS_DIR'"
}

### Remove installed xsession file
function re_uninstall_xsession
{
   $SUDO rm -f "$XSESSIONS_DIR/enlightenment.desktop"
}

###############################################################

### Execute a given command and show the output in a cool dialog, with the 
#   ability to retry, exit or view log
#   On return it set the $RET variable with the return status of the command
function re_execute
{
   local CMD=$1    #ARG1: The command to execute
   local DIR=$2    #ARG2: The directory where the command must be executed
   local TITLE=$3  #ARG3: The title of the dialog
   local TEXT=$4   #ARG4: The header text of the dialog
   local ERR=$5    #ARG5: The error to show if the command fail

   ## uncomment this for debug
   #$DIALOG --title "Debug" --msgbox "EXECUTE:\n$CMD\n\nPATH:\n"`pwd`"\n" $DEF_H $DEF_W
   #return;

   #$CMD 2> /dev/null | $DIALOG --guage "gauge" $DEF_H $DEF_W 0   ## WITH GAUGE
   #$CMD &> "$_temp" | $DIALOG --tailbox "$_temp" $DEF_H $DEF_W   ## WITH TAILBOX

   pushd $DIR >/dev/null
   echo "----------------------------------------------------" > "$_log"
   echo "Command: '$CMD'" >> "$_log"
   echo "----------------------------------------------------" >> "$_log"
   ( eval $CMD ) 2>&1 | tee -a "$_log" | $DIALOG --sleep "$DELAY" \
                                 --backtitle "$BTITLE" --title "$TITLE" \
                                 --progressbox "$TEXT" 50 100
   RET=${PIPESTATUS[0]}
   popd >/dev/null

   [ "$RET" == 0 ] && return

   re_error_message "$ERR"
   if [ "$_ret" == 0 ]; then   # pressed 'Retry'
      re_execute "$CMD" "$DIR" "$TITLE" "$TEXT" "$ERR";
   fi
   if [ "$_ret" == 3 ]; then   # pressed 'Skip', do a fake good result
      RET=0
   fi
}

### Show a simple messagge dialog
function re_message
{
   local MSG=$1    #ARG1: The messagge to show
   $DIALOG --backtitle "$BTITLE" --title " Report " \
           --msgbox "$MSG" $DEF_H $DEF_W
}

###  Show a dialog with an error messagge and the ability to press:
#    Retry, Skip, Exit or 'Show log'
# return values found in "$_ret":     0=retry   1=exit   3=skip
function re_error_message
{
   local MSG=$1    #ARG1: The messagge to show
   
   $DIALOG --backtitle "$BTITLE" --title "  !! ERROR !!  " \
           --help-button --help-label "View log" \
           --extra-button --extra-label "Skip" \
           --ok-label "Retry" --cancel-label "Exit" \
           --yesno "$MSG" $DEF_H $DEF_W
   _ret=$?
   if [ "$_ret" == 2 ]; then  # pressed 'Show log'
      re_show_log;
      re_error_message "$MSG";
   fi
}

### Show a dialog with the contents of the log file
function re_show_log
{
   $DIALOG --backtitle "$BTITLE" --exit-label "Back" \
           --title " Log file   [Up] [Down] [Left] [Right] to scroll " \
           --textbox "$_log" $DEF_H $DEF_W
}

### Exit the program with error
function re_exit
{
   local ret=$1

   rm -f $_temp
   rm -f $_temp_list
   [ "$ret" == 0 ] && clear
   echo "$PNAME: EXIT WITH RES $ret"
   exit $ret
}


###############################################################
# And finally the main :)
###############################################################

_temp="/tmp/reasye17.$$"
_temp_list="/tmp/reasye17_list.$$"
_pwd=`pwd`
_log="$_pwd/.reasye17.log"
_conf="$_pwd/.reasye17.conf"


# check missing packages descriptions...I always forgot them
for p in ${DEFAULT_LIST[@]}; do
   if [ -z "${DESCRS[$p]}" ]; then
      echo "ERROR: missing description for package $p."
      exit 255
   fi
done

# check missing package urls...this is mandatory
for p in ${FULL_LIST[@]}; do
   if [ -z "${VCS_URLS[$p]}" ]; then
      echo "ERROR: missing url for package $p."
      exit 255
   fi
done

# check dialog
if ! type $DIALOG >/dev/null 2>&1; then
   echo "Warning: '$DIALOG' not found. I will try to install it."
   $SUDO apt-get -f install $DIALOG  # try apt-get
   if [ "$?" != 0 ]; then
      $SUDO yum -y install $DIALOG   # try yum
      if [ "$?" != 0 ]; then
         $SUDO urpmi $DIALOG         # try urpmi
      fi
   fi
   if ! type $DIALOG >/dev/null 2>&1; then
      echo "Error: can't install '$DIALOG'."
      echo "     Probably your distribution is not supported at the moment."
      echo "     Dialog is needed by $PNAME to work. You can install $DIALOG by"
      echo "     hand and retry."
      exit 254
   fi
fi

# set some PATHS
export PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$PREFIX/lib/pkgconfig"
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$PREFIX/lib/"


# welcome dialog
$DIALOG --backtitle "$BTITLE" --title " Welcome to $PNAME v$PVER " \
        --msgbox "${WELCOME}" $DEF_H $DEF_W \
        || re_exit 1


# load the config file or show config menu
[ -e $_conf ] && source $_conf || re_config_menu


# main loop
while true; do
  re_main_menu
done


###############################################################
# Changelog
###############################################################

#### 0.4.2 ####
# - added support for bazar repos
# - added three KayHuuhko's apps to the list
# - added 2 mesa pkgs to debian (needed on deb7 for opengl)

#### 0.4.1 ####
# - more packages moved to git
# - fix PKG download when the target dir do not exists.
# - updated debian pkgs list
# - added PYTHON var to let the install work for py3

#### 0.4.0 ####
# - new support for git, now reasy can manage vcs from external sources too!
# - new support for tar packages (prefix the url with PKG:)
# - new support for distutils
# - Cython is now a normal package :)
# - added an option to view the output of the configure script (logs)
# - redone packages list (now a mixed svn/git tree)
# - some new deps: libsndfile1 libmount libblkid and more
# - FIX: no more in the wrong dir if a command fail

#### 0.3.2 ####
# - new packages list, included the new efl tree
# - removed uninstall and remove sources menu entry, useless and not working
# - new custom system, user can now create custom list of packages :)
# - added Update to mainmenu, it's like doing Download + Build
# - dialogs size now automatic, seems better

#### 0.3.1 ####
# - and finally support spaces in descriptions :)
# - better dialog auto-installation
# - clear the term on exit only when successfully quit
# - support packages without description (not in default list)
# - support packages with just a Makefile, like themes

#### 0.3.0 ####
# - New 'Skip' button on failed operations
# - Code review
# - Packages lists reviewed
# - Dropped fedora support

#### 0.2.10 ####
# - removed some dead packages (etk, ewl and the deps)

#### 0.2.9 ####
# - epsilon moved to OLD/

#### 0.2.8 ####
# - Exalt goes out of PROTO/

 
#### 0.2.7 ####
# - Add liblua5.1-dev to debian like distro
# - Etk moved to OLD/

#### 0.2.6 ####
# - Merge download and compile operations
# - Various changes on the packages lists


#### 0.2.5 ####
# - Read number of cpu core and add -j option to the make command

#### 0.2.4 ####
# - Remove po directory on svn-update to fix autopoint issue
# - Add libfontconfig-dev to ubuntu dependencies
# - Fixed some packages description
# - Remove a warning on svn-update

#### 0.2.3 ####
# - Add exchange
# - Add places
# - Support ubuntu 8.10
# - Cvs needed by autopoint
# - Fix generation of config info for evas and ecore
# - Fix installation of xsession file

#### 0.2.2 ####
# - Also eet needs eina

#### 0.2.1 ####
# - Add Eina

#### 0.2.0 ####
# - switch from CVS to SVN
# - some packages added/removed

#### 0.1.1 ####
# - add distro: ubuntu7, debian 5
# - del packages: mixer
# - del packages: mpdule (as it require glib2-dev)
# - add packages: weather
# - add dep: all the needed by the full install
# - fix e_modules/forecast name (e_modules/forecasts)
# - create evas.info and ecore.info files
# - add -P to cvs checkout (it remove empty directory)
# - less debug info
# - on "all operation completed" message write what is finished

#### 0.1.0 #### 
# - initial revision
#
###############################################################
